<template>
    <div>
        <!-- 
        父传子，渲染商品列表
       -->
        <MyTable :arr="list">
            <template v-slot:head>
                <th>#</th>
                <th>商品名称</th>
                <th>价格</th>
                <th>标签</th>
                <th>操作</th>
            </template>
            <!-- 解构赋值 -->
            <template #body="{row}">
                <td>{{row.id}}</td>
                <td>{{row.goods_name}}</td>
                <td>{{row.goods_price}}</td>
                <td>
                    <input type="text" 
                    v-fff 
                    v-model="row.inputValue" 
                    @keydown.esc="row.inputValue=''" 
                    @keydown.enter="enterFn(row)"
                    @blur="row.inputVisible=false" 
                    v-if="row.inputVisible"
                    class="tag-input form-control" style="width: 100px;">
                    <button v-else style="display: block;" class="btn btn-primary btn-sm add-tag" @click="row.inputVisible = true">+Tag</button>
                    <span v-for="(item,i) in row.tags" :key="i" class="badge badge-warning">{{item}}</span>
                </td>
                <td>
                    <button @click="delFn(row.id)" class="btn btn-danger btn-sm">删除</button>
                </td>
            </template>
        </MyTable>
    </div>
</template>

<script>
import MyTable from '../components/MyTable'

export default {
    components: {
        MyTable,
    },
    data() {
        return {
            list: [], // 所有数据
        }
    },
    created() {
        this.$axios({
            url: '/api/goods',
        })
            .then((res) => (this.list = res.data.data))
            .catch((err) => console.log(err))
    },
    methods: {
        delFn(id) {
            this.list = this.list.filter((item) => item.id !== id)
        },
        enterFn(row) {
          if(!row.inputValue.trim()) return alert('xxx，不要不输东西就按回车')
          row.tags.push(row.inputValue)
          row.inputValue=''
        }
    },
    directives: {
        fff: {
            // 绑定指令的元素插入到页面时执行
            inserted(el) {
                el.focus()
            },
        },
    },
}
</script>